package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.config.minio.properties.AppMinioPrpperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName FileUploadServiceImpl
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-10-31 23:53
 * @Version 1.0
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    AppMinioPrpperties appMinioPrpperties;

    @Override
    public String uploadToMinio(MultipartFile file) {
        try {

            //1）抽取到配置文件中，让代码读取配置文件的值
            //2）如何让任何代码直接可以 @Autowired的方式拿到MinioClient 而不是自己new

            //1、创建出MinioClient 端口号给9001报错


            //2、判断桶是否存在
            if(!minioClient.bucketExists(appMinioPrpperties.getBucketName())) {
                minioClient.makeBucket(appMinioPrpperties.getBucketName());
            }

            //3、上传文件
            String date = DateUtil.formatDate(new Date());
            String objectName = date + "/" + UUID.randomUUID().toString().replace("-", "") + "_" + file.getOriginalFilename();

            InputStream inputStream = file.getInputStream();

            //参数
            PutObjectOptions options =
                    new PutObjectOptions(inputStream.available(),-1L);
            //需要设置文件类型,并设置默认为对象流,不能预览
            options.setContentType(file.getContentType());

            minioClient.putObject(appMinioPrpperties.getBucketName(),objectName,inputStream,options);

            //4、返回文件的访问地址
            //String url = "http://192.168.81.81:9000/gmall/" + objectName;
            String url = appMinioPrpperties.getEndpoint() + "/" + appMinioPrpperties.getBucketName() + "/" + objectName;
            return url;
        } catch(Exception e) {
            System.out.println("Error occurred: " + e);
            return null;
        }


    }
}
